import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart' hide SnackPosition;
import 'package:intl/intl.dart';
import 'package:go_router/go_router.dart';

import '../../common/index.dart';
import 'index.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({super.key});

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  late ChatController controller;

  @override
  void initState() {
    super.initState();
    // 初始化并注入控制器
    controller = Get.put(ChatController());

    // 使用WidgetsBinding确保context已准备好
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initializeWithRouterParams();
    });
  }

  // 从go_router中获取参数并传递给控制器
  void _initializeWithRouterParams() {
    final GoRouterState state = GoRouterState.of(context);
    if (state.extra != null && state.extra is Map<String, dynamic>) {
      final Map<String, dynamic> params = state.extra as Map<String, dynamic>;
      if (params.containsKey('userId')) {
        // 手动设置控制器参数
        controller.target_user_id = params['userId'];
        controller.init_data();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      // 点击空白处关闭键盘
      onTap: () => FocusScope.of(context).unfocus(),
      child: Scaffold(
        body: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(AssetsImages.mineBg),
              fit: BoxFit.cover,
            ),
          ),
          child: _buildView(),
        ),
      ),
    );
  }

  // 主视图
  Widget _buildView() {
    return Column(
      children: [
        // 顶部留白区域
        SizedBox(height: 75.h),

        // 聊天主容器
        Expanded(
          child: Container(
            width: double.infinity,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [Color(0xFFFAE9FF), Color(0xFFFFF39A), Colors.white],
                stops: [0.0, 0.5, 0.8],
                tileMode: TileMode.clamp,
              ),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.r),
                topRight: Radius.circular(20.r),
              ),
            ),
            child: Column(
              children: [
                // 顶部操作栏
                _buildHeader(),

                // 聊天消息区域
                Expanded(
                  child: Obx(
                    () => controller.chat_messages.isEmpty
                        ? _buildEmptyChat()
                        : _buildChatMessages(),
                  ),
                ),

                // 输入区域
                _buildInputArea(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 头部区域
  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          InkWell(
            onTap: () => RouteUtil.pop(),
            child: Container(
              width: 35.w,
              height: 35.h,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [Color(0xFFFEED01), Color(0xFFB3A1FE)],
                ),
              ),
              child: Center(
                child: Icon(Icons.close, color: Colors.black, size: 18.sp),
              ),
            ),
          ),

          // 举报按钮
          GestureDetector(
            onTap: () => _showReportDialog(context),
            child: Container(
              width: 35.w,
              height: 35.h,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [Color(0xFFFEED01), Color(0xFFB3A1FE)],
                ),
              ),
              child: Center(
                child: SvgPicture.asset(
                  AssetsImages.report,
                  width: 18.w,
                  height: 18.h,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 空聊天视图
  Widget _buildEmptyChat() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            "No messages yet",
            style: TextStyle(color: Colors.black54, fontSize: 16.sp),
          ),
          SizedBox(height: 10.h),
          Text(
            "Start a conversation",
            style: TextStyle(color: Colors.black38, fontSize: 14.sp),
          ),
        ],
      ),
    );
  }

  // 聊天消息列表
  Widget _buildChatMessages() {
    // 当消息列表更新后滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) {
      controller.scroll_to_bottom();
    });

    return ListView.builder(
      controller: controller.scroll_controller,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
      itemCount: controller.chat_messages.length,
      reverse: false,
      itemBuilder: (context, index) {
        final message = controller.chat_messages[index];
        final isMe = message.spend_user_id == controller.current_user_id;

        // 是否需要显示日期分割线
        bool showDateDivider = false;
        if (index == 0) {
          showDateDivider = true;
        } else {
          final prev_message = controller.chat_messages[index - 1];
          final prevDate = DateTime.parse(
            prev_message.created_time,
          ).toLocal().day;
          final currentDate = DateTime.parse(message.created_time).toLocal().day;
          showDateDivider = prevDate != currentDate;
        }

        return Column(
          children: [
            if (showDateDivider) _buildDateDivider(message.created_time),
            _buildMessageItem(message, isMe),
          ],
        );
      },
    );
  }

  // 日期分割线
  Widget _buildDateDivider(String dateString) {
    final date = DateTime.parse(dateString);
    final today = DateTime.now();
    String formattedDate;

    if (date.year == today.year &&
        date.month == today.month &&
        date.day == today.day) {
      formattedDate = "Today";
    } else if (date.year == today.year &&
        date.month == today.month &&
        date.day == today.day - 1) {
      formattedDate = "Yesterday";
    } else {
      formattedDate = DateFormat('MMM d, yyyy').format(date);
    }

    return Container(
      margin: EdgeInsets.symmetric(vertical: 16.h),
      child: Row(
        children: [
          Expanded(child: Divider(color: Colors.black12)),
          SizedBox(width: 10.w),
          Text(
            formattedDate,
            style: TextStyle(color: Colors.black45, fontSize: 12.sp),
          ),
          SizedBox(width: 10.w),
          Expanded(child: Divider(color: Colors.black12)),
        ],
      ),
    );
  }

  // 单个消息项
  Widget _buildMessageItem(ChatModel message, bool isMe) {
    final time = DateFormat(
      'HH:mm',
    ).format(DateTime.parse(message.created_time).toLocal());

    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        mainAxisAlignment: isMe
            ? MainAxisAlignment.end
            : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isMe)
            // 对方的头像
            Container(
              width: 35.w,
              height: 35.h,
              margin: EdgeInsets.only(right: 8.w),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image:
                      controller.target_user.value?.avatar_image != null &&
                          controller.target_user.value!.avatar_image!.isNotEmpty
                      ? ImagePath().get_avatar_image(
                          controller.target_user.value!.avatar_image!,
                        )
                      : AssetImage(AssetsImages.defaultAvatar),
                  fit: BoxFit.cover,
                ),
              ),
            ),

          // 消息内容及时间
          Column(
            crossAxisAlignment: isMe
                ? CrossAxisAlignment.end
                : CrossAxisAlignment.start,
            children: [
              // 消息气泡
              Container(
                constraints: BoxConstraints(maxWidth: 250.w),
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  borderRadius: isMe
                      ? BorderRadius.only(
                          topLeft: Radius.circular(20.r),
                          topRight: Radius.circular(0.r),
                          bottomLeft: Radius.circular(20.r),
                          bottomRight: Radius.circular(20.r),
                        )
                      : BorderRadius.only(
                          topLeft: Radius.circular(0.r),
                          topRight: Radius.circular(20.r),
                          bottomLeft: Radius.circular(20.r),
                          bottomRight: Radius.circular(20.r),
                        ),
                  border: Border.all(
                    color: isMe ? Color(0xFFB7A5EF) : Color(0xFFFDEC06),
                    width: 1,
                  ),
                ),
                child: Text(
                  message.detail,
                  style: TextStyle(
                    color: Colors.black87,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),

              // 时间显示
              Padding(
                padding: EdgeInsets.only(top: 4.h),
                child: Text(
                  time,
                  style: TextStyle(color: Colors.black45, fontSize: 10.sp),
                ),
              ),
            ],
          ),

          if (isMe)
            // 自己的头像
            Container(
              width: 35.w,
              height: 35.h,
              margin: EdgeInsets.only(left: 8.w),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image:
                      UserService().get_now_user()?.avatar_image != null &&
                          UserService().get_now_user()!.avatar_image!.isNotEmpty
                      ? ImagePath().get_avatar_image(
                          UserService().get_now_user()!.avatar_image!,
                        )
                      : AssetImage(AssetsImages.defaultAvatar),
                  fit: BoxFit.cover,
                ),
              ),
            ),
        ],
      ),
    );
  }

  // 输入区域
  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      decoration: BoxDecoration(color: Colors.transparent),
      child: SafeArea(
        top: false,
        child: Row(
          children: [
            // 输入框
            Expanded(
              child: Container(
                height: 44.h,
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                decoration: BoxDecoration(
                  color: Color(0xFFE0D9FF),
                  borderRadius: BorderRadius.circular(40.r),
                ),
                child: TextField(
                  controller: controller.text_controller,
                  style: TextStyle(color: Colors.black87),
                  decoration: InputDecoration(
                    hintText: "Message...",
                    hintStyle: TextStyle(color: Colors.black45),
                    border: InputBorder.none,
                  ),
                ),
              ),
            ),

            SizedBox(width: 10.w),

            // 发送按钮
            GestureDetector(
              onTap: controller.send_message,
              child: Container(
                width: 60.w,
                height: 44.h,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [Color(0xFFFEED01), Color(0xFFB3A1FE)],
                    stops: [0.1264, 0.887],
                    transform: GradientRotation(115 * 3.14159 / 180),
                  ),
                  borderRadius: BorderRadius.circular(40.r),
                ),
                child: Center(
                  child: Text(
                    "Send",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 从底部显示举报对话框
  void _showReportDialog(BuildContext context) {
    // 检查用户是否登录
    final currentUser = UserService().get_now_user();
    if (currentUser == null) {
      // 提示用户登录
      SmartDialogHelper.show_snackbar(
        title: 'Instruction',
        message: 'Please log in first before reporting',
        backgroundColor: Colors.orange,
        colorText: Colors.white,
      );
      RouteUtil.push(RouteNames.login);
      return;
    }

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        padding: EdgeInsets.all(20.r),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [Color(0xFFFAE9FF), Color(0xFFFFF39A), Colors.white],
            stops: [0.0, 0.5, 0.8],
          ),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(30.r),
            topRight: Radius.circular(30.r),
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              spreadRadius: 0,
              offset: Offset(0, -2),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Handle indicator
            Container(
              width: 40.w,
              height: 5.h,
              margin: EdgeInsets.only(bottom: 16.h),
              decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.3),
                borderRadius: BorderRadius.circular(3.r),
              ),
            ),

            Text(
              'Report User',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),

            SizedBox(height: 8.h),

            Text(
              'This will hide all previous chat messages with this user',
              style: TextStyle(fontSize: 13.sp, color: Colors.black54),
              textAlign: TextAlign.center,
            ),

            SizedBox(height: 24.h),

            _buildReportButton(context, 'Pornographic vulgarity'),
            SizedBox(height: 10.h),
            _buildReportButton(context, 'Privacy Concerns'),
            SizedBox(height: 10.h),
            _buildReportButton(context, 'Hate speech'),
            SizedBox(height: 10.h),
            _buildReportButton(context, 'Nauseating'),
            SizedBox(height: 10.h),
            _buildReportButton(context, 'Illegal'),
            SizedBox(height: 10.h),
            _buildReportButton(context, 'Other'),
            SizedBox(height: 10.h),
            _buildReportButton(context, 'Block'),
            SizedBox(height: 24.h),
            _buildReportButton(context, 'Cancel'),

            // Extra bottom padding for safe area
            SizedBox(height: 10.h),
          ],
        ),
      ),
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(30.r)),
      ),
    );
  }

  // 构建单个举报按钮
  Widget _buildReportButton(BuildContext context, String text) {
    final isCancel = text == 'Cancel';

    return Container(
      width: double.infinity,
      height: 44.h,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: ElevatedButton(
        onPressed: () {
          if (isCancel) {
            Navigator.pop(context);
          } else {
            controller.report_user(context, text);
          }
        },
        style:
            ElevatedButton.styleFrom(
              padding: EdgeInsets.zero,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(40.r),
              ),
              elevation: 0,
            ).copyWith(
              backgroundColor: MaterialStateProperty.all(Colors.transparent),
              overlayColor: MaterialStateProperty.resolveWith((states) {
                return states.contains(MaterialState.pressed)
                    ? Colors.black12
                    : null;
              }),
            ),
        child: Ink(
          decoration: BoxDecoration(
            gradient: isCancel
                ? null
                : LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [Color(0xFFFEED01), Color(0xFFB3A1FE)],
                    stops: [0.1264, 0.887],
                    transform: GradientRotation(115 * 3.14159 / 180),
                  ),
            color: isCancel ? Colors.white.withOpacity(0.8) : null,
            borderRadius: BorderRadius.circular(40.r),
            border: isCancel
                ? Border.all(color: Colors.grey.withOpacity(0.3), width: 1)
                : null,
          ),
          child: Container(
            alignment: Alignment.center,
            child: Text(
              text,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: isCancel ? Colors.black87 : Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
